package com.bawei.module_home.ui.adapter

import android.util.Log
import com.bawei.module_home.data.HomeItem
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.bawei.module_home.databinding.ItemHomeBinding

/**
 * 房源列表适配器
 * 支持根据ID快速获取特定房源数据
 */
class HomeAdapter : ListAdapter<HomeItem, HomeAdapter.HomeViewHolder>(HomeDiffCallback()) {

    // 定义点击事件接口（参数明确为 HomeModel）
    var onItemClickListener: ((HomeItem) -> Unit)? = null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HomeViewHolder {
        val binding = ItemHomeBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return HomeViewHolder(binding)
    }

    override fun onBindViewHolder(holder: HomeViewHolder, position: Int) {
        val item = getItem(position)
        holder.bind(item)
    }

    inner class HomeViewHolder(private val binding: ItemHomeBinding) :
        androidx.recyclerview.widget.RecyclerView.ViewHolder(binding.root) {

        fun bind(item: HomeItem) {
            // 数据绑定（如果布局用了 <data> 声明 HomeModel）
            binding.home = item
            binding.executePendingBindings()

            // 点击事件触发
            binding.root.setOnClickListener {
                onItemClickListener?.invoke(item)
            }
        }
    }

    // DiffUtil 回调：用于高效更新列表
    class HomeDiffCallback : DiffUtil.ItemCallback<HomeItem>() {
        override fun areItemsTheSame(oldItem: HomeItem, newItem: HomeItem): Boolean {
            return oldItem.id == newItem.id // 假设 HomeModel 有 id 字段作为唯一标识
        }

        override fun areContentsTheSame(oldItem: HomeItem, newItem: HomeItem): Boolean {
            return oldItem == newItem // 若数据类未重写 equals，需逐一比较字段
        }
    }
    override fun submitList(list: List<HomeItem>?) {
        super.submitList(list)
        Log.d("HomeAdapter", "接收数据: ${list?.size ?: 0} 条") // 确认数据传递
    }
}